package us.gaaoc.framework.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Service;

import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.util.db.JdbcTemplated;
import us.gaaoc.framework.util.db.ResultSetUtils;

@JdbcTemplated
@Service
public class TagService {
	
	private JdbcTemplate template;

	@Autowired
	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}
	
	public static final String FIND_TAG   =	"select * from caseRecordTags where caseRecordUuid = ? and personUuid = ?;";
	public static final String COUNT_TAGS   =	"select count(*) from caseRecordTags where caseRecordUuid = ? and personUuid = ?;";
	public static final String INSERT_TAG = "insert into caseRecordTags (caseRecordUuid,personUuid) values (?,?);";
	public static final String DELETE_TAG = "delete from caseRecordTags where caseRecordUuid = ? and personUuid = ?;";
	
	public TagService() {
		
	}

	public boolean isTagged(CaseRecord cr, Person p) {		
		return ! (0 == template.queryForInt(COUNT_TAGS, new Object[] { cr.getUuid(), p.getUuid() }));		 
	}
	
	public void tag(CaseRecord cr, Person p)
	{		
		template.update(INSERT_TAG,cr.getUuid(),p.getUuid());
	}
	
	public void untag(CaseRecord cr, Person p)
	{
		template.update(DELETE_TAG,cr.getUuid(),p.getUuid());
	}
	
	public void toggle(CaseRecord cr, Person p)
	{
		if(isTagged(cr,p))
		{
			untag(cr,p);
		}else{
			tag(cr,p);
		}
	}
	

}
